#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import urllib
import urllib2
import logging


class MoJoQQ:
    def __init__(self, mojo_host='127.0.0.1', mojo_port='3000'):
        """
        MoJoQQ webqq的perl实现可以使用它发送、接收qq消息

        Args:
            mojo_host (str): MoJoQQ 主机地址
            mojo_host (str): MoJoQQ 服务端口
        """
        self.mojo_host = mojo_host
        self.mojo_port = mojo_port
        self.mojo_url = 'http://%s:%s' % (self.mojo_host, self.mojo_port)

    def send_group_msg(self, group_num, msg):
        """
        发送qq群组消息
            /openqq/send_group_message
                id: 群组的id（每次扫描登录可能会变化）
                uid: 群号码
                content:消息内容(中文需要做urlencode)
                async: 0或1,可选,是否异步发送消息
        Args:
            group_num (str): 群号码
            msg (str): 消息
        Returns:
            str: json
        """
        service_path = '/openqq/send_group_message'

        encoded_data = urllib.urlencode({
            'uid': group_num,
            'content': msg.encode('utf-8')
        })
        logging.info("full url %s" % ('%s?%s' % (self.mojo_url + service_path, encoded_data)))
        try:
            resp = urllib2.urlopen('%s?%s' % (self.mojo_url + service_path, encoded_data)).read()
            logging.info("mojo qq resp %s " % resp)
        except Exception as e:
            logging.info("发送QQ群组消息失败 %s " % e.message)
